package com.suxin.shiro.config;

import com.suxin.shiro.cache.RedisCacheManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Tang
 * @classname ShiroConfig
 * @description [  ]
 * @date 2021/3/21 11:01
 */
//@Configuration
public class ShiroConfig {

    /**
     * realm 设置
     * @return
     */
    @Bean
    Realm realm(RedisTemplate<String, Object> redisTemplate) {
        MyRealm myRealm = new MyRealm();
        // 加密+盐值

        // 开启缓存
        myRealm.setCacheManager(new RedisCacheManager(redisTemplate));
        myRealm.setCachingEnabled(true);
        myRealm.setAuthorizationCachingEnabled(true);
        myRealm.setAuthorizationCacheName("AuthorizationCache");
        myRealm.setAuthenticationCacheName("AuthenticationCache");
        myRealm.setAuthenticationCachingEnabled(true);
        return myRealm;
    }

    /**
     * filter 设置
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) throws Exception {
        Map<String, String> hashMap = new LinkedHashMap<>(16);
        // 放行登录接口
        hashMap.put("/user/login", "anon");
        hashMap.put("/user/loginOut", "anon");
        hashMap.put("/user/error", "anon");
        // authc:请求这个资源需要认证
        hashMap.put("/user/**","authc");
        hashMap.put("/**","authc");

        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        // 设置登录 url,没权限的时候跳转
        filterFactoryBean.setLoginUrl("/login.jsp");
        filterFactoryBean.setSuccessUrl("/**");
        // 没权限
        filterFactoryBean.setUnauthorizedUrl("/user/error");
        filterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        filterFactoryBean.setFilterChainDefinitionMap(hashMap);
        return filterFactoryBean;
    }

    /**
     * 权限管理器设置
     * @return
     */
    @Bean
    DefaultWebSecurityManager defaultWebSecurityManager(RedisTemplate<String, Object> redisTemplate) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm(redisTemplate));
        return securityManager;
    }

}